package com.huaxiafinance.management.util;

import com.huaxiafinance.management.dto.request.CaptchaDto;
import com.huaxiafinance.management.model.CaptchaSession;
import nl.captcha.Captcha;
import nl.captcha.servlet.CaptchaServletUtil;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public final class CaptchaUtil
{
    private CaptchaUtil()
    {
        throw new Error("工具类不能实例化");
    }

    public static void getCaptcha(final HttpSession session, HttpServletResponse response,
                                  CaptchaDto dto)
    {
        getCaptcha(session, response, dto, 160, 40);
    }

    public static void getCaptcha(final HttpSession session, HttpServletResponse response,
                                  CaptchaDto dto, int width, int height)
    {
        Captcha localCaptcha = new Captcha.Builder(width, height).addText().addNoise().build();
        CaptchaServletUtil.writeImage(response, localCaptcha.getImage());
        CaptchaSession cs = new CaptchaSession(dto.getCaptcha(), localCaptcha.getAnswer());
        session.setAttribute(dto.getCaptcha(), cs.getCode());
    }

    public static void resetCaptcha(final HttpSession session)
    {
        session.setAttribute("simpleCaptcha", null);
    }

    public static boolean checkCaptcha(final HttpSession session, String checkCode)
    {
        Captcha localCaptcha = (Captcha)session.getAttribute("simpleCaptcha");
        if (localCaptcha == null)
        {
            return false;
        }
        return localCaptcha.isCorrect(checkCode);
    }
}
